﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

using Furion;
using MiniExcelLibs;

namespace Abc.Web.Mvc.Areas.HtAdmin.Controllers;

[MaMvc( controllerDescription: "用户", PCode = "HtAdmin_User")]
public class UserController : HtAdminBaseController
{
    private readonly ILogger<UserController> _logger;
    private readonly IUserService _userService;
    private readonly HtRoleService _roleService;
    private readonly IHtAccountService _accountService;

    public UserController(ILogger<UserController> logger
      , IUserService userService
      , HtRoleService roleService
      , IHtAccountService accountService)
    {
        _logger = logger;
        _userService = userService;
        _roleService = roleService;
        _accountService = accountService;
    }

    [MaMenu(name: "用户列表", CreateDate = "2021-07-31")]
    [MaPermission(name: "用户列表", actions: "Index,GetList")]
    [HttpGet]
    public async Task<IActionResult> Index()
    {
        ViewBag.LoginUser = await _accountService.GetLoginUser();
        return View();
    }

    [UnifyResult(typeof(HtUserOut))]
    [HttpPost, HttpGet]
    public async Task<JsonResult> GetList(HtUserQuery searchquery)
    {
        var pagedlist = await _userService.GetAllByPageToLayui(searchquery);
        return Json(pagedlist);
    }

    [MaPermission(name: "编辑", actions: "Info")]
    public async Task<ActionResult> Info(long? id)
    {
        ViewBag.LoginUser = await _accountService.GetLoginUser();
        ViewBag.Roles = (await _roleService.GetAll()).Where(o => o.IsEnable).ToList();
        HtUserOut entity = null;
        if (id.HasValue)
        {
            entity = await _userService.Get(id.Value);
        }
        return View(entity ?? new HtUserOut());
    }

    public async Task<IActionResult> Add()
    {
        ViewBag.Roles = (await _roleService.GetAll()).Where(o => o.IsEnable).ToList();
        ViewBag.LoginUser = await _accountService.GetLoginUser();

        return View("Info", new HtUserOut() { IsEnable = true });
    }

    [HttpPost]
    public async Task<JsonResult> Edit(HtUserInput input)
    {
        await _userService.InsertOrUpdate(input);
        return Json("");
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [MaPermission(name: "删除", actions: "Delete")]
    [HttpPost]
    public async Task<ActionResult> Delete(long ids)
    {
        await _userService.Delete(ids);
        return Json("");
    }

    /// <summary>
    /// 批量删除
    /// </summary>
    /// <param name="ids">需要删除数据，多个英文逗号隔开</param>
    /// <returns></returns>
    [HttpPost]
    [MaPermission(name: "批量删除", actions: "BatchDelete")]
    public async Task<ActionResult> BatchDelete(string ids)
    {
        await _userService.BatchDelete(ids);
        return Json("");
    }

    [MaPermission(name: "设置状态", actions: "SetState")]
    [HttpPost]
    public async Task<JsonResult> SetState(long id, bool state, string type)
    {
        await _userService.SetState(id, state, type);
        return Json("");
    }

    [MaMenu(name: "测试用户信息页面", CreateDate = "2021-07-31")]
    [MaPermission(name: "测试用户信息页面", actions: "TestInfo,GetList")]
    public async Task<IActionResult> TestInfo()
    {
        ViewBag.Roles = (await _roleService.GetAll()).Where(o => o.IsEnable).ToList();
        ViewBag.LoginUser = await _accountService.GetLoginUser();
        return View();
    }



    /// <summary>
    /// 下载Excel列表（保存到内存，然后直接下载）
    /// 参考文档：https://gitee.com/dotnetchina/MiniExcel#excel-%E5%88%97%E5%B1%9E%E6%80%A7-excel-column-attribute-
    /// </summary>
    /// <returns></returns>
    [MaPermission(name: "下载Excel列表", actions: "DownloadExcel")]
    public async Task<IActionResult> DownloadExcel(HtUserQuery searchquery)
    {
        var pagedlist = await _userService.GetAllByPageToLayui(searchquery);

        var memoryStream = new MemoryStream();
        memoryStream.SaveAs(pagedlist.data);//直接在内存创建然后以流的方式返回
        memoryStream.Seek(0, SeekOrigin.Begin);
        return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            FileDownloadName = "用户列表.xlsx"
        };
    }

    /// <summary>
    ///下载Excel列表，（使用模板，保存到内存，然后直接下载）
    /// </summary>
    /// <returns></returns>
    [MaPermission(name: "下载Excel列表", actions: "DownloadExcel")]
    public async Task<IActionResult> DownloadExcel2(HtUserQuery searchquery)
    {
        var pagedlist = await _userService.GetAllByPageToLayui(searchquery);

        string templatePath = $"{App.WebHostEnvironment.WebRootPath}\\Templates\\用户列表模板.xlsx";
        //byte[] bytes = System.IO.File.ReadAllBytes(templatePath);

        //注意：模板填充 外面要封装一层 value,否则会报错的 https://gitee.com/dotnetchina/MiniExcel#2-ienumerable-%E6%95%B0%E6%8D%AE%E5%A1%AB%E5%85%85

        //下面这个rows可以是自己的数据
        var value = new {
            data = pagedlist.data
        };

        var memoryStream = new MemoryStream();
        memoryStream.SaveAsByTemplate(templatePath, value);
        memoryStream.Seek(0, SeekOrigin.Begin);
        return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            FileDownloadName = "用模板导出的用户列表.xlsx"
        };
    }

}